package com.csf.controller.interceptor;

import com.csf.annotation.intercpAnnotation;
import com.csf.entity.SessionReplace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class AnnotationIntercepter implements HandlerInterceptor {

     @Autowired
     private SessionReplace sessionReplace;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        首先判断申请的路径是方法还是其他
         if (handler instanceof HandlerMethod){
//             强转诚方法
             HandlerMethod method = (HandlerMethod) handler;
//           从该方法中获取是否有自定义注解
             Method method1 = method.getMethod();
             intercpAnnotation annotation = method1.getAnnotation(intercpAnnotation.class);
//             如果自定义注解作用于该方法上，并且没有用户登录，就不能访问此路径
             if (annotation != null && sessionReplace.getUser() == null){
                 response.sendRedirect(request.getContextPath()+"/login");
                 return false;
             }
         }
        return true;
    }
}
